#!/usr/bin/env python3
"""
===============================================================================
 SOVEREIGN BUILDER ORCHESTRATOR (v7.0)
 Author: Thomas B. Sweet
 Description: Bootstraps the build environment, reads YAML config,
              and prepares context for Gemini 3 Pro code generation.
===============================================================================
"""

import os
import sys
import subprocess
import platform
import venv
import shutil

# --- CONFIGURATION ---
BUILDER_VENV = "launcher_venv"
REQUIRED_PACKAGES = ["pyyaml", "google-generativeai", "requests"]
MASTER_CONFIG = "MASTER.YAML"
DEFAULT_CONFIG = "DEFAULT.YAML"

def log(msg):
    print(f"\033[1;36m[ORCHESTRATOR]\033[0m {msg}")

def error(msg):
    print(f"\033[1;31m[ERROR]\033[0m {msg}")
    sys.exit(1)

def bootstrap_venv():
    """Ensures a clean Python environment for the builder."""
    python_bin = os.path.join(BUILDER_VENV, "bin", "python")
    pip_bin = os.path.join(BUILDER_VENV, "bin", "pip")

    if platform.system() == "Windows":
        python_bin = os.path.join(BUILDER_VENV, "Scripts", "python.exe")
        pip_bin = os.path.join(BUILDER_VENV, "Scripts", "pip.exe")

    if not os.path.exists(BUILDER_VENV):
        log(f"Creating isolated environment: {BUILDER_VENV}...")
        venv.create(BUILDER_VENV, with_pip=True)

    # Check for required packages
    try:
        subprocess.check_call([python_bin, "-c", "import yaml; import google.generativeai"],
                              stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    except subprocess.CalledProcessError:
        log("Installing builder dependencies...")
        subprocess.check_call([pip_bin, "install"] + REQUIRED_PACKAGES)

    return python_bin

def read_config(python_bin, config_file):
    """Reads the YAML configuration using the venv python."""
    py_script = f"""
import yaml
try:
    with open('{config_file}', 'r') as f:
        data = yaml.safe_load(f)
        print(f"LOADED: {{data['meta']['project_name']}} v{{data['meta']['version']}}")
except Exception as e:
    print(f"FAIL: {{e}}")
"""
    result = subprocess.run([python_bin, "-c", py_script], capture_output=True, text=True)
    if "FAIL:" in result.stdout:
        error(f"Could not parse {config_file}. Check syntax.")
    else:
        print(result.stdout.strip())

def main():
    log("Initializing Sovereign Builder...")

    # 1. Environment Setup
    python_exec = bootstrap_venv()

    # 2. Config Detection
    target_config = MASTER_CONFIG if os.path.exists(MASTER_CONFIG) else DEFAULT_CONFIG
    log(f"Target Configuration: {target_config}")
    read_config(python_exec, target_config)

    # 3. Preparation for AI Handoff
    print("\n" + "="*60)
    print(" READY FOR AI GENERATION")
    print("="*60)
    print(f"1. Please ensure 'Gemini_API.key' is in the root folder.")
    print(f"2. The environment '{BUILDER_VENV}' is ready.")
    print(f"3. In the next session, the AI will read '{target_config}'")
    print("   and generate the C++ source files in '/sourcecode/src/'.")
    print("-" * 60)
    print("COMMAND TO RUN GENERATION (Next Step):")
    print(f"{python_exec} generate_code.py --config {target_config}")
    print("="*60)

if __name__ == "__main__":
    main()
